#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author: LiangChao
@email：kevinleong1011@hotmail.com

@desc: 
"""
from makitest.grammar.errors import KeywordRegisteredError
from makitest.grammar.keyword import Keyword


class GrammarManager:
    """语法管理器"""

    def __init__(self):
        self.keywords = {}

    def register(self, name, func, grammar_fmt):
        """
        注册语法关键字，将其与实际的API方法建立映射关系
        :param name: keyword name
        :param func: API func
        :param grammar_fmt: 语法格式，执行时会依靠格式将表达式中包含的参数提取出来传递给API执行
        :return:
        """
        if name in self.keywords:
            raise KeywordRegisteredError(name, grammar_fmt)
        keyword = Keyword(func, grammar_fmt)
        self.keywords[name] = keyword
        return keyword

    def run_sentence(self, sentence):
        parts = sentence.split(' ', maxsplit=1)
        keyword = parts[0]
        keyword = self.keywords.get(keyword)
        return keyword.run(sentence)

    def grammar(self, name, fmt):
        """A decorator to register a grammar support for api"""
        def deco(func):
            self.register(name, func, fmt)

        return deco

    def translate(self, script, filename=None):
        pass

    def generate_help(self, filename):
        """
        Generate a help file.
        :param filename: filename to be saved
        :return:
        """


manager = GrammarManager()   # default grammar manager
